package model

import (
	"devOpsApi/common/util"
	"devOpsApi/libs"
	"encoding/json"
	"errors"
	"github.com/jinzhu/gorm"
	"math"
)

type Flow struct {
	gorm.Model
	db   *gorm.DB
	Name string      `gorm:"column:name" json:"name,omitempty" form:"name" validate:"required"`
	Cate string      `gorm:"column:cate" json:"cate,omitempty" form:"cate" validate:"required"`
	Sort string      `gorm:"column:sort" json:"sort,omitempty" form:"sort"`
	Flow interface{} `gorm:"column:flow" json:"flow,omitempty" form:"flow" validate:"required"`
}

func (Flow) TableName() string {
	return "flow"
}

func NewFlow() *Flow {
	return &Flow{db: libs.DB}
}

func (m *Flow) List(page, pagesize uint) ([]Flow, uint, uint) {
	var data = []Flow{}
	var totalCount uint
	limit := pagesize
	offset := (page - 1) * limit
	m.db.Model(&Flow{}).Count(&totalCount)
	err := m.db.Model(&Flow{}).Select("id,name,cate,created_at,updated_at").Offset(offset).Limit(limit).Order("cate asc").Find(&data).Error
	if err != nil {
		//log.Fatalln(err)
	}
	totalPages := uint(math.Ceil(float64(totalCount) / float64(limit)))
	return data, totalCount, totalPages
}

func (m *Flow) ListAll() []Flow {
	var data = []Flow{}
	_ = m.db.Model(&Flow{}).Select("id,name,flow,cate,created_at,updated_at").Order("sort desc").Find(&data).Error
	return data
}

func (m *Flow) Create() error {
	if !m.db.Where("name = ?", m.Name).Find(&Flow{}).RecordNotFound() {
		return errors.New("该名称已经存在")
	}
	Flow, _ := json.Marshal(m.Flow)
	m.Flow = string(Flow)
	if err := util.Validate(m); err != nil {
		return err
	}
	return m.db.Create(m).Error
}

func (m *Flow) Update() error {
	if !m.db.Where("name = ? and id != ?", m.Name, m.ID).Find(&Flow{}).RecordNotFound() {
		return errors.New("该名称已经存在")
	}
	Flow, _ := json.Marshal(m.Flow)
	m.Flow = string(Flow)
	if err := util.Validate(m); err != nil {
		return err
	}
	return m.db.Save(m).Error
}

func (m *Flow) Del(id uint) error {
	return m.db.Where("id = ?", id).Delete(m).Error
}

func (m *Flow) Detail(id uint) (flow Flow, err error) {
	err = m.db.Where("id = ?", id).First(&flow).Error
	return
}

func (m *Flow) UpdateFields(id uint, fields map[string]interface{}) error {
	return m.db.Model(&Flow{}).Where("id = ?", id).Updates(fields).Error
}

func (m *Flow) UpdateSuccessNum(id uint) error {
	return m.db.Model(&Flow{}).Where("id = ?", id).UpdateColumn("success_num", gorm.Expr("error_num + ?", 1)).Error
}

func (m *Flow) UpdateErrNum(id uint) error {
	return m.db.Model(&Flow{}).Where("id = ?", id).UpdateColumn("error_num", gorm.Expr("error_num + ?", 1)).Error
}
